import {EventEmitter} from './event'

export class Client extends EventEmitter {
    constructor() {
        super()
        this.callbacks = {}
        this.websocket = null
        this.reqId = 0
        this.errMap = null;
    }

    init(options) {
        let self = this
        if (this.websocket) {
            return
        }

        this.websocket = new WebSocket('ws://' + options.ip + ':' + options.port)

        this.websocket.onopen = function(evt) {
            console.log('连接服务器 ' + 'ws://' + options.ip + ':' + options.port)
            self.emit('socketOpen')
        }

        this.websocket.onclose = function(evt) {
            self.disconnect()
        }

        this.websocket.onmessage = function(message) {
            var data = JSON.parse(message.data)

            if (data.reqId) {
                var i = data.reqId
                var err = ',err:0',
                    route = self.callbacks[i].route

                if (data.err && self.errMap) {
                    if (self.errMap[route] && parseInt(data.err) < 100) {
                        var err = self.errMap[route][data.err]
                        err = ',err-' + data.err + ':' + err
                    } else {
                        var err = self.errMap['getErrMap'][data.err]
                        err = ',err-' + data.err + ':' + err
                    }
                }

                if (self.callbacks[i].cb) {
                    self.callbacks[i].cb(data.err, data.msg)
                }
                delete self.callbacks[i]

                console.log(`接收:(route:${route},reqId:${data.reqId}${err})`, data.msg || '')
            }
            if (data.route) {
                console.log('监听消息: ', data.route, data.msg)
                self.emit(data.route, data.msg)
            }
        }

        this.websocket.onerror = function(evt) {
            console.log('连接出错')
            self.disconnect()
        }
    }

    disconnect() {
        if (this.websocket) {
            if (this.websocket.disconnect) this.websocket.disconnect()
            if (this.websocket.close) this.websocket.close()
            this.websocket = null
            console.log('服务器断开连接')
            this.emit('disconnect')
        }
    }


    request(route, msg, cb) {
        this.reqId += 1
        var data = {
            route: route,
            msg: msg,
            reqId: this.reqId
        }

        this.callbacks[this.reqId] = {
            route: route
        }
        if (cb) {
            this.callbacks[this.reqId].cb = cb
        }
        data = JSON.stringify(data)
        console.log(`发送:(route:${route},reqId:${this.reqId})`, msg)
        this.websocket.send(data)
    }
}
